import logging
import time
import os

from bson import BSON
from bson import json_util
import json

from bson.objectid import ObjectId

from tornado.web import RequestHandler
from tornado.web import authenticated

from tornado.gen import coroutine
from tornado.web import asynchronous

from handlers import BaseHandler, UserBaseHandler
from handlers.admin import AdminBaseHandler


from util.pxfilter import XssHtml
from util.function import intval
import pymongo

'''
数据状态
-10,数据废弃
0,完成数据说明，暂时未完成，可以修改
10，完成元数据说明,可以发布，可以修改
20，已经发布，不可修改，只能废弃
'''


def xss_filter(html):
    parser = XssHtml()
    parser.feed(html)
    parser.close()
    return parser.getHtml()


class IndexHandler(UserBaseHandler):

    @coroutine
    def get(self):

        limit = {'title': 1, 'from': 1, 'dtype': 1, 'updatetime': 1}

        cursor = self.db.dataset.find({'status': 20}, limit)
        datalist = yield cursor.to_list(12)

        self.render('data/index.html', datalist=datalist)


class DetailHandler(UserBaseHandler):

    @coroutine
    def get(self, id):

        detail = yield self.db.dataset.find_one({"_id": ObjectId(id)})

        self.render('data/detail.html', detail=detail)

####
# admin handlers
########


class FormHandler(AdminBaseHandler):

    def get(self):
        self.render('admin/data/form.html')

    @coroutine
    def post(self):

        title = self.get_body_argument('datasetTitle')
        dtype = self.get_body_argument('datasetType')
        note = self.get_body_argument('datasetNote')

        # 验证
        # if not title:
        # …………
        # note = xss_filter(note)

        dataset = {
            "title": title,
            "from": self.current_user['username'],
            "updatetime": time.time(),
            "dtype": dtype,
            "note": note,
            "status": 0,
            "args": [],
        }

        id = yield self.db.dataset.insert(dataset)
        self.redirect("/data/form_meta?oid=%s" % id)


class MetaFormHandler(AdminBaseHandler):

    @coroutine
    def get(self):

        oid = self.get_argument('oid')

        detail = yield self.db.dataset.find_one({"_id": ObjectId(oid)})

        self.render('admin/data/form_meta.html', detail=detail)

    @coroutine
    def post(self, id):
        # 验证

        post = yield self.db.dataset.find_and_modify({
            "_id": ObjectId(id)
        }, {
            "$set": {
                "status": 10
            }
        })

        self.redirect('/admin/data')


class ListHandler(AdminBaseHandler):

    @coroutine
    def get(self):

        page_size = 15

        page = intval(self.get_argument('p', default=None))
        if not page or page <= 0:
            page = 1

        limit = {'title': 1, 'from': 1, 'dtype': 1,
                 'updatetime': 1, 'status': 1}

        data_publish_cur = self.db.dataset.find({"status": 20}, limit)
        data_publish = yield data_publish_cur.to_list(5)

        data_drop_cur = self.db.dataset.find({"status": -10}, limit)
        data_drop = yield data_drop_cur.to_list(5)

        ##
        data_standby_cur = self.db.dataset.find(
            {"status": {"$in": [0, 10]}}, limit)

        page_count = yield data_standby_cur.count()

        data_standby_cur.sort([('updatetime', pymongo.DESCENDING)]).skip(
            (page - 1) * page_size)

        data_standby = yield data_standby_cur.to_list(page_size)

        self.render('admin/data/index.html', data_drop=data_drop,
                    data_publish=data_publish, data_standby=data_standby, data_standby_page=page, data_standby_size=page_size, data_standby_count=page_count)


class DetailAdminHandler(AdminBaseHandler):

    @coroutine
    def get(self, id):

        detail = yield self.db.dataset.find_one({"_id": ObjectId(id)})

        if not detail:
            self.redirect('/admin')

        self.render('admin/data/detail.html', detail=detail)


class PublishHandler(AdminBaseHandler):

    @coroutine
    def get(self):
        oid = self.get_argument('oid')
        detail = yield self.db.dataset.find_and_modify({"_id": ObjectId(oid)}, {
            "$set": {
                "status": 20
            }
        })

        self.redirect('/admin/data')


class CloseHandler(AdminBaseHandler):

    @coroutine
    def get(self, id):
        detail = yield self.db.dataset.find_and_modify({"_id": ObjectId(id)}, {
            "$set": {
                "status": -10
            }
        })

        self.redirect('/admin/data')


class ModifyHandler(AdminBaseHandler):

    @coroutine
    def get(self):

        oid = self.get_argument('oid')

        detail = yield self.db.dataset.find_one({"_id": ObjectId(oid)})

        self.render('admin/data/form_modify.html', detail=detail)

    @coroutine
    def post(self):

        oid = self.get_argument('oid')

        title = self.get_body_argument('datasetTitle')
        dtype = self.get_body_argument('datasetType')
        note = self.get_body_argument('datasetNote')

        # 验证
        # if not title:
        # …………
        # note = xss_filter(note)

        post = yield self.db.dataset.find_and_modify({"_id": ObjectId(oid)}, {
            "$set": {
                "title": title,
                "dtype": dtype,
                "note": note,
                "updatetime": time.time()
            }
        })
        if post:
            self.redirect("/admin/data/%s" % post.get('_id'))


class ModifyMetaHandler(AdminBaseHandler):

    @coroutine
    def get(self):
        oid = self.get_argument('oid')

        detail = yield self.db.dataset.find_one({"_id": ObjectId(oid)})

        self.render('admin/data/form_meta_modify.html', detail=detail)

    @coroutine
    def post(self, id):

        title = self.get_body_argument('datasetTitle')
        dtype = self.get_body_argument('datasetType')
        note = self.get_body_argument('datasetNote')

        # 验证
        # if not title:
        # …………
        # note = xss_filter(note)

        dataset = {
            "title": title,
            "from": self.current_user['username'],
            "updatetime": time.time(),
            "dtype": dtype,
            "note": note,
        }

        id = yield self.db.dataset.insert(dataset)
        self.redirect("/data/show/%s" % id)


class CreateMetaHandler(AdminBaseHandler):

    @coroutine
    def post(self):
        oid = self.get_argument('oid')

        title = self.get_body_argument('argTitle')
        atype = self.get_body_argument('argType')
        note = self.get_body_argument('argNote')

        arg_post = {
            "title": title,
            "updatetime": time.time(),
            "atype": atype,
            "note": note
        }

        post = yield self.db.dataset.find_and_modify({
            "_id": ObjectId(oid)
        }, {
            "$push": {
                "args": {
                    "_id": ObjectId(),
                    "title": title,
                    "atype": atype,
                    "note": note
                }
            },
            "$set": {
                "status": 10,
                "updatetime": time.time()
            }
        })

        if post:
            self.redirect('/admin/data_meta/modify?oid=%s' % post.get('_id'))


class DownloadHandler(UserBaseHandler):

    @asynchronous
    @coroutine
    def get(self):

        current_user = self.current_user
        isComplete = yield self.db.member.find_one({"_id": ObjectId(current_user['_id']), "flag": 0})

        print("%s::::", (type(isComplete)))

        if isComplete is None:
            self.redirect('/auth/userinfo')

        key = self.get_query_argument("key")
        key = os.path.abspath(os.path.join(
            self.settings['download'], key))

        if self.check_exist(key):
            self.set_secure_cookie("download_key", key)
            self.redirect("/download/100.zip")

    def check_exist(self, key):
        return os.path.isfile(key)
